// tablewidget.cpp
#include "tablewidget.h"
#include <QHeaderView>
#include <QInputDialog>
#include <QContextMenuEvent>
#include "channelSetupDialog.h"

TableWidget::TableWidget(QWidget *parent) : QWidget(parent) {
    // 初始化布局和表格
    layout = new QVBoxLayout(this);
    tableWidget = new QTableWidget(0, 0, this); // 初始为 0 行 0 列
    initTable();
    layout->addWidget(tableWidget);
    setLayout(layout);
}

void TableWidget::initTable() {
    // 设置表格样式
    tableWidget->setSortingEnabled(true); // 启用排序
    tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    tableWidget->horizontalHeader()->setSectionsClickable(true); // 允许点击表头
    tableWidget->verticalHeader()->setVisible(false);
    tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);

    // 连接表头点击事件
    connect(tableWidget->horizontalHeader(), &QHeaderView::sectionClicked, this, [this](int column) {
        // 切换排序顺序
        Qt::SortOrder order = tableWidget->horizontalHeader()->sortIndicatorOrder();
        tableWidget->sortItems(column, order == Qt::AscendingOrder ? Qt::DescendingOrder : Qt::AscendingOrder);
    });
}



// 根据数据来源初始化表格
void TableWidget::initFromData(const QList<QMap<QString, QVariant>>& data) {
    tableWidget->setRowCount(0); // 清空表格
    for (const auto& rowData : data) {
        addRow(rowData); // 逐行添加数据
    }
}
// 计算某列的最大值
QVariant TableWidget::getColumnMax(int column) const {
    if (column < 0 || column >= tableWidget->columnCount()) {
        return QVariant();
    }

    QVariant maxValue;
    for (int row = 0; row < tableWidget->rowCount(); ++row) {
        QVariant value;
        if (columnInfos[column].type == "button" || columnInfos[column].type == "progress") {
            // 对于按钮或进度条，返回其状态或值
            QWidget* widget = tableWidget->cellWidget(row, column);
            if (columnInfos[column].type == "button") {
                QPushButton* button = qobject_cast<QPushButton*>(widget);
                if (button) {
                    value = button->isChecked();
                }
            } else if (columnInfos[column].type == "progress") {
                CustomProgressWidget* progressWidget = qobject_cast<CustomProgressWidget*>(widget);
                if (progressWidget) {
                    value = progressWidget->getLeftValue();
                }
            }
        } else {
            // 对于文本列，返回单元格内容
            value = tableWidget->item(row, column)->text();
        }

        if (!maxValue.isValid() || value.toDouble() > maxValue.toDouble()) {
            maxValue = value;
        }
    }
    return maxValue;
}

// 计算某列的最小值
QVariant TableWidget::getColumnMin(int column) const {
    if (column < 0 || column >= tableWidget->columnCount()) {
        return QVariant();
    }

    QVariant minValue;
    for (int row = 0; row < tableWidget->rowCount(); ++row) {
        QVariant value;
        if (columnInfos[column].type == "button" || columnInfos[column].type == "progress") {
            // 对于按钮或进度条，返回其状态或值
            QWidget* widget = tableWidget->cellWidget(row, column);
            if (columnInfos[column].type == "button") {
                QPushButton* button = qobject_cast<QPushButton*>(widget);
                if (button) {
                    value = button->isChecked();
                }
            } else if (columnInfos[column].type == "progress") {
                CustomProgressWidget* progressWidget = qobject_cast<CustomProgressWidget*>(widget);
                if (progressWidget) {
                    value = progressWidget->getLeftValue();
                }
            }
        } else {
            // 对于文本列，返回单元格内容
            value = tableWidget->item(row, column)->text();
        }

        if (!minValue.isValid() || value.toDouble() < minValue.toDouble()) {
            minValue = value;
        }
    }
    return minValue;
}
// 根据指定列排序
void TableWidget::sortByColumn(int column, Qt::SortOrder order) {
    tableWidget->sortItems(column, order);
}

void TableWidget::addColumn(const QString& columnName, const QString& columnType, const QVariant& defaultValue) {
    // 添加列信息
    ColumnInfo info;
    info.type = columnType;
    info.defaultValue = defaultValue;
    columnInfos.append(info);

    // 添加列到表格
    int column = tableWidget->columnCount();
    tableWidget->insertColumn(column);
    tableWidget->setHorizontalHeaderItem(column, new QTableWidgetItem(columnName));
}

void TableWidget::setColumnProperty(int column, const QString& propertyName, const QVariant& value) {
    if (column >= 0 && column < columnInfos.size()) {
        columnInfos[column].properties[propertyName] = value;
    }
}

void TableWidget::addRow(const QMap<QString, QVariant>& rowData) {
    // 插入新行
    int row = tableWidget->rowCount();
    tableWidget->insertRow(row);

    // 填充新行数据
    fillRow(row, rowData);
}

void TableWidget::removeRow(int row) {
    if (row >= 0 && row < tableWidget->rowCount()) {
        tableWidget->removeRow(row);
    }
}

void TableWidget::updateRow(int row, const QMap<QString, QVariant>& rowData) {
    if (row >= 0 && row < tableWidget->rowCount()) {
        // 更新行数据
        fillRow(row, rowData);
    }
}

QMap<QString, QVariant> TableWidget::queryRow(int row) const {
    QMap<QString, QVariant> rowData;
    if (row >= 0 && row < tableWidget->rowCount()) {
        for (int column = 0; column < tableWidget->columnCount(); ++column) {
            QString columnName = tableWidget->horizontalHeaderItem(column)->text();
            QVariant value;
            if (columnInfos[column].type == "button" || columnInfos[column].type == "progress") {
                // 对于按钮或进度条，返回其状态或值
                QWidget* widget = tableWidget->cellWidget(row, column);
                if (columnInfos[column].type == "button") {
                    QPushButton* button = qobject_cast<QPushButton*>(widget);
                    if (button) {
                        value = button->isChecked();
                    }
                } else if (columnInfos[column].type == "progress") {
                    CustomProgressWidget* progressWidget = qobject_cast<CustomProgressWidget*>(widget);
                    if (progressWidget) {
                        value = progressWidget->getLeftValue();
                    }
                }
            } else {
                // 对于文本列，返回单元格内容
                value = tableWidget->item(row, column)->text();
            }
            rowData[columnName] = value;
        }
    }
    return rowData;
}

void TableWidget::refresh() {
    // 清空表格
    tableWidget->clearContents();
    tableWidget->setRowCount(0);

    // 重新填充数据（如果需要）
    // 这里可以根据具体需求实现数据刷新逻辑
}

void TableWidget::fillRow(int row, const QMap<QString, QVariant>& rowData) {
    for (int column = 0; column < tableWidget->columnCount(); ++column) {
        QString columnName = tableWidget->horizontalHeaderItem(column)->text();
        QVariant value = rowData.contains(columnName) ? rowData[columnName] : columnInfos[column].defaultValue;

        if (columnInfos[column].type == "button") {
            // 按钮列
            QPushButton* button = new QPushButton(value.toString(), this);
            button->setCheckable(true);
            button->setStyleSheet("QPushButton:checked { background-color: green; }");
            connect(button, &QPushButton::toggled, this, [button](bool checked) {
                button->setText(checked ? "启用" : "未启用");
            });
            tableWidget->setCellWidget(row, column, button);
        } else if (columnInfos[column].type == "color") {
            // 颜色按钮列
            QPushButton* colorButton = new QPushButton("", this);
            QColor color = value.value<QColor>();
            QPalette palette = colorButton->palette();
            palette.setColor(QPalette::Button, color);
            colorButton->setPalette(palette);
            colorButton->setAutoFillBackground(true);
            colorButton->setFlat(true);
            connect(colorButton, &QPushButton::clicked, this, [this, row, column]() {
                QColor color = QColorDialog::getColor(Qt::white, this, "");
                if (color.isValid()) {
                    tableWidget->item(row, column)->setBackground(color);
                }
            });
            tableWidget->setCellWidget(row, column, colorButton);
        } else if (columnInfos[column].type == "progress") {
            // 进度条列
            CustomProgressWidget* progressWidget = new CustomProgressWidget(this);
            progressWidget->setRange(value.toMap()["min"].toInt(), value.toMap()["max"].toInt());
            progressWidget->setMinMax(value.toMap()["min"].toInt(), value.toMap()["max"].toInt());
            progressWidget->setUnit(value.toMap()["unit"].toString());
            progressWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
            tableWidget->setCellWidget(row, column, progressWidget);
        } else {
            // 文本列
            tableWidget->setItem(row, column, new QTableWidgetItem(value.toString()));
        }
    }
}


void TableWidget::contextMenuEvent(QContextMenuEvent *event) {
    // 创建右键菜单
    QMenu menu(this);
    menu.addAction("增加数据", this, &TableWidget::onAddData);
    menu.addAction("修改数据", this, &TableWidget::onEditData);
    menu.addAction("删除本条数据", this, &TableWidget::onDeleteData);
    menu.addAction("导出数据", this, &TableWidget::onExportData);

    // 显示菜单
    menu.exec(event->globalPos());
}

void TableWidget::onAddData() {
    // 弹出输入对话框
    QMap<QString, QVariant> newData = showInputDialog();
    if (!newData.isEmpty()) {
        addRow(newData); // 添加新数据
    }
}

void TableWidget::onEditData() {

    // 获取当前选中行
    int row = tableWidget->currentRow();
    if (row >= 0) {
        QStringList rowData;
        for (int col = 0; col < tableWidget->columnCount(); ++col) {
            rowData << tableWidget->item(row, col)->text();
        }
        // 弹出对话框
        channelSetupDialog dialog(this);
        dialog.setRowData(rowData); // 传递当前行数据
        // 如果用户点击了 "OK"，更新表格数据
        if (dialog.exec() == QDialog::Accepted) {
            QStringList newData = dialog.getRowData();
            for (int col = 0; col < tableWidget->columnCount(); ++col) {
                tableWidget->item(row, col)->setText(newData[col]);
            }
        }
    } else {
        QMessageBox::warning(this, "警告", "请先选择一行数据！");
    }
}

void TableWidget::onDeleteData() {
    // 获取当前选中行
    int row = tableWidget->currentRow();
    if (row >= 0) {
        removeRow(row); // 删除数据
    } else {
        QMessageBox::warning(this, "警告", "请先选择一行数据！");
    }
}

void TableWidget::onExportData() {
    // 弹出文件保存对话框
    QString fileName = QFileDialog::getSaveFileName(this, "导出数据", "", "CSV 文件 (*.csv)");
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&file);

            // 写入表头
            for (int column = 0; column < tableWidget->columnCount(); ++column) {
                out << tableWidget->horizontalHeaderItem(column)->text();
                if (column < tableWidget->columnCount() - 1) {
                    out << ",";
                }
            }
            out << "\n";

            // 写入数据
            for (int row = 0; row < tableWidget->rowCount(); ++row) {
                for (int column = 0; column < tableWidget->columnCount(); ++column) {
                    if (columnInfos[column].type == "button" || columnInfos[column].type == "progress") {
                        // 对于按钮或进度条，返回其状态或值
                        QWidget* widget = tableWidget->cellWidget(row, column);
                        if (columnInfos[column].type == "button") {
                            QPushButton* button = qobject_cast<QPushButton*>(widget);
                            if (button) {
                                out << (button->isChecked() ? "启用" : "未启用");
                            }
                        } else if (columnInfos[column].type == "progress") {
                            CustomProgressWidget* progressWidget = qobject_cast<CustomProgressWidget*>(widget);
                            if (progressWidget) {
                                out << progressWidget->getLeftValue();
                            }
                        }
                    } else {
                        // 对于文本列，返回单元格内容
                        out << tableWidget->item(row, column)->text();
                    }
                    if (column < tableWidget->columnCount() - 1) {
                        out << ",";
                    }
                }
                out << "\n";
            }

            file.close();
            QMessageBox::information(this, "成功", "数据已导出到 " + fileName);
        } else {
            QMessageBox::warning(this, "错误", "无法打开文件！");
        }
    }
}

QMap<QString, QVariant> TableWidget::showInputDialog(const QMap<QString, QVariant>& initialData) {
    QMap<QString, QVariant> newData;

    // 遍历列信息，弹出输入对话框
    for (int column = 0; column < tableWidget->columnCount(); ++column) {
        QString columnName = tableWidget->horizontalHeaderItem(column)->text();
        QString columnType = columnInfos[column].type;

        QVariant value;
        if (columnType == "button") {
            // 按钮列：弹出选择对话框
            bool ok;
            QStringList options = {"未启用", "启用"};
            QString selected = QInputDialog::getItem(this, "输入", columnName, options, initialData.value(columnName, "未启用").toString() == "启用" ? 1 : 0, false, &ok);
            if (ok) {
                value = selected;
            } else {
                return {}; // 用户取消输入
            }
        } else if (columnType == "color") {
            // 颜色列：弹出颜色选择对话框
            QColor defaultColor = QColor(Qt::white); // 将 Qt::white 转换为 QColor 对象
            QColor color = QColorDialog::getColor(initialData.value(columnName, QVariant::fromValue(defaultColor)).value<QColor>(), this, columnName);
            if (color.isValid()) {
                value = color;
            } else {
                return {}; // 用户取消输入
            }
        } else if (columnType == "progress") {
            // 进度条列：弹出输入对话框
            bool ok;
            int min = initialData.value(columnName).toMap()["min"].toInt();
            int max = initialData.value(columnName).toMap()["max"].toInt();
            int currentValue = initialData.value(columnName).toMap()["value"].toInt();
            int valueInput = QInputDialog::getInt(this, "输入", columnName, currentValue, min, max, 1, &ok);
            if (ok) {
                value = QVariantMap({{"min", min}, {"max", max}, {"value", valueInput}, {"unit", "单位"}});
            } else {
                return {}; // 用户取消输入
            }
        } else {
            // 文本列：弹出输入对话框
            bool ok;
            QString text = QInputDialog::getText(this, "输入", columnName, QLineEdit::Normal, initialData.value(columnName, "").toString(), &ok);
            if (ok) {
                value = text;
            } else {
                return {}; // 用户取消输入
            }
        }

        newData[columnName] = value;
    }

    return newData;
}
